"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

interface Event {
  id: string
  title: string
  description: string | null
  date: string
  libraryId: string
}

export default function EditEventPage({
  params: { id }
}: {
  params: { id: string }
}) {
  const router = useRouter()
  const [event, setEvent] = useState<Event | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    fetchEvent()
  }, [id])

  async function fetchEvent() {
    try {
      const response = await fetch(`/api/admin/events/${id}`)
      if (!response.ok) throw new Error("加载失败")
      const data = await response.json()
      setEvent(data)
    } catch (err) {
      setError("无法加载事件")
    } finally {
      setLoading(false)
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!event) return

    setSaving(true)
    try {
      const response = await fetch(`/api/admin/events/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: event.title,
          description: event.description,
          date: event.date
        })
      })

      if (!response.ok) throw new Error("保存失败")
      router.push(`/admin/libraries/${event.libraryId}`)
      router.refresh()
    } catch (err) {
      setError("保存事件失败")
    } finally {
      setSaving(false)
    }
  }

  if (loading) return <div className="text-center p-8">加载中...</div>
  if (error) return <div className="text-red-500 text-center p-8">{error}</div>
  if (!event) return <div className="text-center p-8">事件不存在</div>

  return (
    <div className="max-w-2xl mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">编辑事件</h1>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">标题</label>
          <Input
            value={event.title}
            onChange={e => setEvent(prev => prev ? { ...prev, title: e.target.value } : null)}
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">描述</label>
          <Textarea
            value={event.description || ""}
            onChange={e => setEvent(prev => prev ? { ...prev, description: e.target.value } : null)}
            rows={4}
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">日期</label>
          <Input
            type="date"
            value={new Date(event.date).toISOString().split('T')[0]}
            onChange={e => setEvent(prev => prev ? { ...prev, date: e.target.value } : null)}
            required
          />
        </div>

        <div className="flex space-x-4">
          <Button type="submit" disabled={saving}>
            {saving ? "保存中..." : "保存"}
          </Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => router.push(`/admin/libraries/${event.libraryId}`)}
          >
            取消
          </Button>
        </div>
      </form>
    </div>
  )
} 